<?php
/**
 * 检查上一天编辑过的订单的结算金额
 * @author yiwan
 */

ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Doraemon\amqp\Queue;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Classes\SettlementTransaction as clsSettlementTransaction;
use Doraemon\tools\Log as toolsLog;
use Biz\model\settlement\Settlement as mSettlement;
use Biz\tools\Mail;

$t1 = microtime(true);
var_dump('检查脚本开始时间：' . date('Y-m-d H:i:s'));

$startTime = date('Y-m-d', strtotime('-1 days'));
$endTime = date('Y-m-d H:i:s', strtotime("+1 days -1 second", strtotime($startTime)));
$orderList = mOrder::select('*', ['edittime[>=]' => $startTime, 'edittime[<=]' => $endTime, 'pay_way[!]' => '', 'pay_no[!]' => '', 'status' => [mOrder::STATUS_SUCCESS, mOrder::STATUS_CLOSE]]);
if ($orderList) {
    $orderNos = array_column($orderList, 'order_no');
    $refundArr = mOrderRefund::select('*', ['order_no' => $orderNos, 'status' => mOrderRefund::STATUS_COMPLETE]);
    $refundList = [];
    foreach ($refundArr as $row) {
        $refundList[$row['order_no']][] = $row;
    }
    $i = 0;
    foreach ($orderList as $orderInfo) {
        $orderNo = $orderInfo['order_no'];
        $orderRefundList = (isset($refundList[$orderNo]) && $refundList[$orderNo]) ? $refundList[$orderNo] : [];

        checkSettlementAmount($orderInfo, $orderRefundList);

        var_dump('检查订单(' . ($i + 1) . ')：' . $orderNo . ' 结束');

        $i++;
    }

    var_dump($startTime . '至' . $endTime . '订单，共检查' . $i . '个订单');
}
$t2 = microtime(true);
$time = $t2 - $t1;
$mtime = ($time * 1000);
var_dump('检查脚本结束时间：' . date('Y-m-d H:i:s'));
var_dump("检查脚本使用时间:" . number_format($time, 2) . '秒 ' . $mtime . '毫秒');


function checkSettlementAmount($orderInfo, $orderRefundList)
{
    $orderNo = $orderInfo['order_no'];
    $settlementArr = mSettlement::select('*', ['order_no' => $orderNo]);
    $settlementTransactionAmount = 0;
    foreach ($settlementArr as $row) {
        $settlementTransactionAmount = bcadd($settlementTransactionAmount, $row['transaction_amount'], 2);
    }
    $payAmount = $orderInfo['pay_amount'];
    $integralAmount = $orderInfo['integral_amount'];
    $couponAmount = $orderInfo['coupon_amount'];
    $activityAllowance = $orderInfo['activity_allowance'];
    $packetAmount = $orderInfo['packet_amount'];
    $commissions = $orderInfo['commissions'];


    $refundSuccessSum = [
        'rmb' => 0,
        'integral_amount' => 0,
        'coupon_amount' => 0,
        'activity_allowance' => 0,
        'packet_amount' => 0,
        'commissions' => 0,
    ];
    if ($orderRefundList) {//如果有退款，需要订单金额减去退款的各种金额来计算结算金额
        foreach ($orderRefundList as $row) {
            $refundSuccessSum['rmb'] = bcadd($refundSuccessSum['rmb'], $row['refund_rmb'], 2);
            $refundSuccessSum['rmb'] = bcadd($refundSuccessSum['rmb'], $row['refund_shipping_amount'], 2);

            $refundSuccessSum['integral_amount'] = bcadd($refundSuccessSum['integral_amount'], $row['refund_integral_amount'], 2);
            $refundSuccessSum['coupon_amount'] = bcadd($refundSuccessSum['coupon_amount'], $row['refund_coupon_amount'], 2);
            $refundSuccessSum['activity_allowance'] = bcadd($refundSuccessSum['activity_allowance'], $row['refund_activity_allowance'], 2);
            $refundSuccessSum['packet_amount'] = bcadd($refundSuccessSum['packet_amount'], $row['refund_packet_amount'], 2);
            $refundSuccessSum['commissions'] = bcadd($refundSuccessSum['commissions'], $row['refund_commission_amount'], 2);
        }

        $payAmount = bcsub($orderInfo['pay_amount'], $refundSuccessSum['rmb'], 2);
        $integralAmount = bcsub($orderInfo['integral_amount'], $refundSuccessSum['integral_amount'], 2);
        $couponAmount = bcsub($orderInfo['coupon_amount'], $refundSuccessSum['coupon_amount'], 2);
        $activityAllowance = bcsub($orderInfo['activity_allowance'], $refundSuccessSum['activity_allowance'], 2);
        $packetAmount = bcsub($orderInfo['packet_amount'], $refundSuccessSum['packet_amount'], 2);
        $commissions = bcsub($orderInfo['commissions'], $refundSuccessSum['commissions'], 2);

    }
    $settlementAmount = 0;
    $settlementAmount = bcadd($settlementAmount, $payAmount, 2);
    $settlementAmount = bcadd($settlementAmount, $integralAmount, 2);
    $settlementAmount = bcadd($settlementAmount, $couponAmount, 2);
    $settlementAmount = bcadd($settlementAmount, $activityAllowance, 2);
    $settlementAmount = bcadd($settlementAmount, $packetAmount, 2);
    $settlementAmount = bcsub($settlementAmount, $commissions, 2);

    var_dump('订单结算账户结算金额：' . $settlementTransactionAmount . '#订单结算金额：' . $settlementAmount);
    if ($settlementTransactionAmount != $settlementAmount) {
        $msg = '检查订单结算金额错误';
        $errArr = [
            'order_no' => $orderInfo['order_no'],
            'uid' => $orderInfo['uid'],
            'settlement_amount' => $settlementAmount,
            'settlement_transaction_amount' => $settlementTransactionAmount,
            'status' => $orderInfo['status'],
            'shop_id' => $orderInfo['shop_id'],
            'pay_amount' => $payAmount,
            'integral_amount' => $integralAmount,
            'coupon_amount' => $couponAmount,
            'activity_allowance' => $activityAllowance,
            'packet_amount' => $packetAmount,
            'commissions' => $commissions,
            'is_refunded' => $orderRefundList ? 1 : 0,
            'refund_success_sum_amount' => $refundSuccessSum,
            'order_info_amount' => [
                'pay_amount' => $orderInfo['pay_amount'],
                'integral_amount' => $orderInfo['integral_amount'],
                'coupon_amount' => $orderInfo['coupon_amount'],
                'activity_allowance' => $orderInfo['activity_allowance'],
                'commissions' => $orderInfo['commissions'],
            ]
        ];
        toolsLog::settlement_checkSettlementAmount_warning($msg, $errArr);
        Queue::insertQueue("queue/Wechatnotice/toTag", [
            "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
            "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
        ], Queue::QUEUE_BIZ);
        $sendMail = [
            'tangyiwan@haohaozhu.com',
        ];
        Mail::send($sendMail, '检查订单结算金额错误', $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
    }

}



